package com.xuecheng.auth.service.ucenter.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.auth.model.dto.AuthParamsDto;
import com.xuecheng.auth.model.dto.XcUserExt;
import com.xuecheng.auth.model.po.XcMenu;
import com.xuecheng.auth.service.service.XcMenuService;
import com.xuecheng.auth.service.service.XcUserService;
import com.xuecheng.auth.service.ucenter.AuthService;
import com.xuecheng.base.utils.JsonCopyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Component
public class UserServiceImpl implements UserDetailsService {
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private XcMenuService xcMenuService;
    @Autowired
    private XcUserService xcUserService;

    @Override
    public UserDetails loadUserByUsername(String authParamsDto) throws UsernameNotFoundException {

        AuthParamsDto authParams = JsonCopyUtil.parseOrThrow(authParamsDto, AuthParamsDto.class, () -> new RuntimeException("请求内容不合法"));
        String beanName = authParams.getAuthType() + "_authservice";
        AuthService authService = applicationContext.getBean(beanName, AuthService.class);
        XcUserExt xcUserExt = authService.execute(authParams);      //调用统一execute认证方法
        return getUserPrincipal(xcUserExt);      //将用户数据封装为 UserDetails
    }

    private UserDetails getUserPrincipal(XcUserExt xcUserExt) {
        String[] authorities = {"test"};
        List<XcMenu> xcMenus = xcMenuService.selectPermissionByUserId(xcUserExt.getId());

        if(xcMenus.size()>0){
            List<String> permissions = xcMenus.stream().map(m -> m.getCode()).collect(Collectors.toList());
            authorities = permissions.toArray(new String[0]);
        }
        String userJson = JSON.toJSONString(xcUserExt);
        return User.withUsername(userJson).password(xcUserExt.getPassword()).authorities(authorities).build();
    }

}
















